package com.sls.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.sls.common.constant.AuthServerConstant;
import com.sls.common.exception.BizCodeEnume;
import com.sls.common.utils.R;
import com.sls.mall.auth.feign.MemberFeignService;
import com.sls.common.vo.MemberRespVo;
import com.sls.mall.auth.vo.UserLoginVO;
import com.sls.mall.auth.vo.UserRegistVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
        String rediscode = code + "_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,rediscode,10L, TimeUnit.MINUTES);

        System.out.println("验证码为："+code);
//        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    /**
     * RedirectAttributes redirectAttributes 模拟重定向携带参数
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVO vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            //Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(
                    FieldError::getField,
                    FieldError::getDefaultMessage,

                    // 没有这一句 会报错
                    (entity1,entity2) -> entity1
            ));
            //问题： 为防止表达重复提交 需要使用转发，但转发无法携带参数，
            //解决方法：启用model.addAttribute("errors", errors); 改用redirectAttributes.addFlashAttribute("errors", errors);
            //model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);

            //问题：表单转到了IP 没有转到域名 return "redirect:/reg.html";
            // 解决：全部使用完整地址转发
            //校验出错，转发到注册页
            return "redirect:http://auth.slsmall.com/reg.html";
        }
        // 调用远程服务注册
        //1.校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(StringUtils.isNotEmpty(s) && code.equals(s.split("_")[0])){
            redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
            R r = memberFeignService.regist(vo);
            if(r.getCode() == 0){
                //成功
                return "redirect:http://auth.slsmall.com/login.html";
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.slsmall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.slsmall.com/reg.html";
        }
    }

    /**
     * 账户登录
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0){
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            log.info("登录成功：用户：{}", data.toString());
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://www.slsmall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.slsmall.com/login.html";
        }


    }
}
